package com.devunion.bogdan.view.editors;

import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

/**
 * User: user
 * Date: 11.02.2005
 * Time: 20:49:44
 */

/**
 * Class for specifying special behaviour of groups of buttons.
 * It is similar to standart </code>ButtonGroup<code> class in AWT.
 */
public class ToggleButtonGroup {
    protected List<AbstractButton> buttons = new ArrayList<AbstractButton>();

    public void add(final AbstractButton b) {
        if (b == null) {
            return;
        }

        b.getModel().addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {

                    for (AbstractButton button : buttons) {
                        if (!button.equals(b)) {
                            button.setSelected(false);
                        }
                    }
                }
            }
        });

        if (b.isSelected()) {
            deselectAll();
        }
        buttons.add(b);
    }

    public void remove(AbstractButton b) {
        if (b == null) {
            return;
        }
        buttons.remove(b);
    }

    public boolean contains(AbstractButton button) {
        return buttons.contains(button);
    }

    public void setSelected(AbstractButton button, boolean b) {
        if (b && button != null) {
            deselectAll();
            button.setSelected(true);
        }
    }

    public void deselectAll() {
        for (AbstractButton button : buttons) {
            button.setSelected(false);
        }
    }
}
